package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.mta.pokerstats.Team;

/**
 * Servlet implementation class servletTeam
 */
public final class servletTeam extends BaseRecordsAbstractServlet {
	private static final long serialVersionUID = 1L;

	protected void processInsertRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Team team;
			String teamName = request.getParameter("teamName");
			int teamLeaderID = Integer.parseInt(request.getParameter("teamLeaderID"));
			team = new Team(-1, teamName, teamLeaderID);
			if (team.InsertToDatabase()) {
				out.print("{" + k_SuccessStr + " , \"teamID\" : \"" + team.getId() +"\"}");
			} else {
				out.print("{" + k_FailStr + "}");
			}
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	@Override
	protected void processUpdateRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Team team;
			int teamID = Integer.parseInt(request.getParameter("teamID"));
			String teamName = request.getParameter("teamName");
			int teamLeaderID = Integer.parseInt(request.getParameter("teamLeaderID"));

			team = Team.getTeamById(teamID);
			team.setName(teamName);
			team.setTeamLeaderId(teamLeaderID);
			if (team.UpdateInDatabase()) {
				out.print("{" + k_SuccessStr + "}");
			} else {
				out.print("{" + k_FailStr + "}");
			}
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

	protected void processDeleteRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Team team;
			int teamID = Integer.parseInt(request.getParameter("teamID"));
			team = Team.getTeamById(teamID);
			if (team.DeleteFromDatabase()) {
				out.print("{" + k_SuccessStr + "}");
			} else {
				out.print("{" + k_FailStr + "}");
			}
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}
}